package com.itheima.shiro;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
/**
 * shiro配置类
 */
import org.springframework.context.annotation.Configuration;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;

@Configuration
public class ShiroConfig {

	/*
	 * 创建三个bean
	 */
	@Bean
	public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager) {
		/**
		 * 添加shiro内置过滤器 实现登录拦截功能
		 * anon : 无需认证登录就可以访问
		 * authc :必须认证才可以访问
		 * user : 必须使用remerberMe的功能才能使用
		 * perms: 该资源必须得到资源权限才可以访问
		 * role: 该资源必须得到角色权限才可以访问
		 * 拦截成功之后 默认跳转到login.jsp
		 */
				
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(securityManager);
		Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
		
		filterChainDefinitionMap.put("/testThymeleaf", "anon");
		filterChainDefinitionMap.put("/login", "anon");
		//实现授权
		filterChainDefinitionMap.put("/add","perms[user:add]");
		filterChainDefinitionMap.put("/update","perms[user:update]");
		//这个要最后写
		filterChainDefinitionMap.put("/*", "authc");
		//修改跳转的页面
		shiroFilterFactoryBean.setLoginUrl("/toLogin");
		
		//跳转的未授权页面
		shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
		return shiroFilterFactoryBean;
	}
	
	/**
	 * 创建defaultWebSecurityManager
	 */
	@Bean(name = "securityManager")
	public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm) {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setRealm(userRealm);
		return securityManager;
		
	}
	
	
	/**
	 * 创建Realm
	 * @return
	 */
	@Bean(name = "userRealm")
	public UserRealm getRealm() {
		return new UserRealm();
	}
	
	/**
	 * 配置ShiroDialect 用于thymeleaf和shiro标签整合
	 * @return
	 */
	@Bean
	public ShiroDialect getShiroDialect() {
		return new ShiroDialect();
	}
	
}
